package com.shop.shop_end.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shop.shop_end.entity.Admin;
import com.shop.shop_end.exception.ServiceException;
import com.shop.shop_end.mapper.AdminMapper;
import com.shop.shop_end.service.AdminService;
import com.shop.shop_end.utils.CommonUtil;
import com.shop.shop_end.utils.GenerateIdUtil;
import com.shop.shop_end.utils.MD5Util;
import com.shop.shop_end.utils.TokenUtils;
import com.shop.shop_end.utils.result.Result;
import com.shop.shop_end.utils.result.ResultUtil;
import com.shop.shop_end.variable.EnableVariable;
import com.shop.shop_end.variable.ErrorCodeEnum;
import com.shop.shop_end.dto.LoginUser;
import com.shop.shop_end.variable.RoleVariable;
import com.shop.shop_end.vo.AdminVo;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class AdminServiceImpl implements AdminService {
    final Logger logger = LoggerFactory.getLogger(AdminServiceImpl.class);

    @Resource
    private CommonUtil commonUtil;
    @Resource
    private AdminMapper adminMapper;

    @Override
    public Result getAllAdmins() {
        List<Admin> adminList = adminMapper.selectList(new QueryWrapper<>());
        return ResultUtil.ok(adminList);
    }

    @Override
    public Admin getAdminById(Long adminId) {
        return adminMapper.selectById(adminId);
    }

    @Override
    @Transactional
    public Result addAdmin(Admin admin) {
        try {
            admin.setAdminId(GenerateIdUtil.generateId());
            //密码加密
            String md5 = MD5Util.generateMD5(admin.getPassword());
            admin.setPassword(md5);
            //设置创建时间
            admin.setCreateTime(new Date());
            int res = adminMapper.insert(admin);
            if (res == 1){
                logger.info("注册成功，admin==>{}", admin);
                return ResultUtil.ok(admin);
            }else {
                logger.info("增加管理员数据时出现数据库异常，admin==>{}", admin);
                return ResultUtil.error("注册过程中出现未知异常！", admin);
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.info("增加管理员到mysql出现异常,admin==>{}", admin);
            throw new ServiceException(ErrorCodeEnum.SQL_INSERT_ERROR, "插入出现异常");
        }
    }

    @Override
    @Transactional
    public Result updateAdmin(Admin admin) {
        try {
            int res = adminMapper.updateById(admin);
            if (res == 1){
                logger.info("修改成功，admin==>{}", admin);
                return ResultUtil.ok(admin);
            }else {
                logger.info("修改失败，admin==>{}", admin);
                return ResultUtil.error("修改出现异常", admin);
            }
        }catch (Exception e) {
            e.printStackTrace();
            logger.info("mysql修改管理员失败");
            throw new ServiceException(ErrorCodeEnum.SQL_UPDATE_ERROR, "修改失败");
        }
    }

    @Override
    @Transactional
    public Result deleteAdmin(Long adminId) {
        try {
            int delete = adminMapper.deleteById(adminId);
            if (delete == EnableVariable.ENABLE) {
                logger.info("删除成功");
                return ResultUtil.ok();
            }
            return ResultUtil.fail("删除出现异常");
        }catch (Exception e) {
            e.printStackTrace();
            logger.info("删除出现异常");
            throw new ServiceException(ErrorCodeEnum.SQL_DELETE_ERROR, "删除出现异常");
        }
    }

    //通过用户名查找管理员
    @Override
    public Result getAdminByName(String username) {
        try {
            QueryWrapper<Admin> wrapper = new QueryWrapper<>();
            wrapper.eq("username", username);
            Admin admin = adminMapper.selectOne(wrapper);
            return ResultUtil.ok(admin);
        }catch (Exception e){
            e.printStackTrace();
            logger.info("mysql根据用户名查找管理员失败");
            throw new ServiceException(ErrorCodeEnum.SQL_QUERY_ERROR, "数据库查找失败");
        }
    }

    /**
     * 管理员登录
     * @param admin
     * @return
     */
    @Override
    public Result login(LoginUser admin) {
        String username = admin.getUsername();
        String password = admin.getPassword();
        try {
            QueryWrapper<Admin> wrapper = new QueryWrapper<>();
            wrapper.eq("username", username);
            Admin isExistAdmin = adminMapper.selectOne(wrapper);
            if (isExistAdmin == null) {
                logger.info("该账号不存在，username：{}", username);
                return ResultUtil.fail("该账号不存在", username);
            }
            QueryWrapper<Admin> wrapper1 = new QueryWrapper<>();
            //密码加密
            String md5 = MD5Util.generateMD5(admin.getPassword());
            wrapper1.eq("username", username);
            wrapper1.eq("password", md5);//使用加密后的密码与数据库进行比较
            Admin res = adminMapper.selectOne(wrapper1);
            System.out.println("res: " + res);
            if (res == null) {
                logger.info("登录失败，密码错误！");
                return ResultUtil.fail("登录失败，请检查用户名和密码", res);
            }
            logger.info("登录成功！admin: " + res.toString());
//            Admin admin1 = (Admin) this.commonUtil.getSession().getAttribute("admin");
//            System.out.println("admmin1===>"+admin1.getAdminId());
            AdminVo adminVo = new AdminVo();
            adminVo.setAdminId(res.getAdminId());
            adminVo.setAvatar(res.getAvatar());
            adminVo.setUsername(res.getUsername());
            adminVo.setPassword(res.getPassword());
            adminVo.setRealName(res.getRealName());
            adminVo.setContact(res.getContact());
            adminVo.setCreateTime(res.getCreateTime());
            //设置token
            adminVo.setToken(TokenUtils.generateToken(res.getAdminId(), RoleVariable.ROLE_ADMIN, res.getPassword()));
            this.commonUtil.getSession().setAttribute("admin", adminVo);
            return ResultUtil.ok(adminVo);
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("查找数据库失败");
            throw new ServiceException(ErrorCodeEnum.SQL_QUERY_ERROR, "查找异常");
        }
    }
}
